package com.example.api.service.impl;

import com.example.api.constant.StatusConst;
import com.example.api.dto.UserDTO;
import com.example.api.mapper.UserMapper;
import com.example.api.query.UserQuery;
import com.example.api.service.UserService;
import com.example.api.pojo.User;
import com.example.api.utils.PageResult;
import com.example.api.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Value("${example.password}")
    private String password;


    @Resource
    UserMapper userMapper;



    @Override
    public PageResult<UserVO> find(UserQuery userQuery) {

        userQuery.setJump((userQuery.getPage()-1)*userQuery.getPageSize());
        List<UserVO> userVOList = userMapper.find(userQuery);

        long total = userMapper.findCount(userQuery);

        PageResult<UserVO> page = new PageResult();
        page.setList(userVOList);
        page.setTotal(total);
        return page;
    }

    @Override
    public void add(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);

        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        user.setStatus(StatusConst.ACTIVE_STATUS);

        userMapper.add(user);
    }

    @Override
    public UserVO login(String loginName, String password) {
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        return userMapper.login(loginName,password);
    }

    @Override
    public void update(long id, UserDTO userDTO) {
        //dto -- > pojo
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);

        user.setId(id);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    public void deleteById(long id) {
        userMapper.deleteById(id);
    }

    @Override
    public void updateStatus(long id, byte status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }
}